<template>
  <view>
    <u-popup :show="showGoodsSku" @close="close" round="10" :closeable="true">
      <view class="popDialog">
        <view class="goods boxPanel">
          <image
            :src="$util.img(goodsDetail.sku_image, { size: 'mid' })"
            mode="aspectFit"
            class="img"
            lazy-load
          ></image>
          <view class="" style="width: 68%">
            <view class="font-30 ellipsis-2">{{ goodsDetail.sku_name }}</view>
            <view
              class="font-40 c-origin flex-y-baseline text-bold"
              v-if="goodsType == 'pintuan'"
            >
              <text class="font-24">¥</text>{{ goodsDetail.pintuan_price }}
            </view>
            <view class="font-40 c-origin flex-y-baseline text-bold" v-else>
              <text class="font-24">¥</text>{{ goodsDetail.price }}
            </view>
          </view>
        </view>
        <scroll-view :scroll-y="true" class="sku">
          <view
            class="boxPanel"
            v-for="(item, index) in goodsDetail.goods_spec_format"
            :key="index"
          >
            <view class="m-b-24 text-bold">{{ item.spec_name }}</view>
            <view
              class="skuItem"
              v-for="(item_value, index_value) in item.value"
              :key="index_value"
              :class="{
                selected: item_value['selected'] || skuId == item_value.sku_id,
                disabled:
                  item_value['disabled'] ||
                  (!item_value['selected'] && disabled),
              }"
              @click="change(item_value.sku_id, item_value.spec_id)"
            >
              <text>{{ item_value.spec_value_name }}</text>
            </view>
          </view>

          <view class="flex-between numbox boxPanel">
            <view>
              <text>数量</text>
              <text class="limit-txt color-title2" v-if="limitNumber > 0"
                >(每人限购{{ limitNumber }}{{ goodsDetail.unit }})</text
              >
              <text
                v-if="maxBuy > 0 && minBuy > 1"
                class="limit-txt color-title2"
              >
                ({{ minBuy }}{{ goodsDetail.unit }}起售，限购{{ maxBuy
                }}{{ goodsDetail.unit }})
              </text>
              <text v-else-if="maxBuy > 0" class="limit-txt color-title2"
                >(限购{{ maxBuy }}{{ goodsDetail.unit }})</text
              >
              <text v-else-if="minBuy > 1" class="limit-txt color-title2"
                >({{ minBuy }}{{ goodsDetail.unit }}起售)</text
              >
            </view>
            <view class="quantity-control">
              <view class="btn-minus" @click="decreaseQuantity()">-</view>
              <input
                type="number"
                v-model="number"
                class="quantity"
                @blur="blur"
              />
              <view class="btn-plus color-title2" @click="increaseQuantity()"
                >+</view
              >
            </view>
          </view>
        </scroll-view>

        <view class="footer fixfooter">
          <block v-if="goodsType == 'pintuan'">
            <view
              class="btn_com btn_buy"
              style="width: 690rpx"
              @click="confirm('pintuan')"
              >立即购买</view
            >
          </block>
          <block v-else>
            <view class="btn_com btn_cart" @click="confirm('join_cart')"
              >加入购物车</view
            >
            <view class="btn_com btn_buy" @click="confirm('buy_now')"
              >立即购买</view
            >
          </block>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  name: "goods-sku",
  props: {
    showGoodsSku: {
      type: Boolean,
      default: false,
    },
    goodsDetail: {
      type: Object,
      default: null,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    maxBuy: {
      type: Number,
      default: 0,
    },
    minBuy: {
      type: Number,
      default: 0,
    },
    goodsType: {
      //商品类型  pintuan 拼团商品
      type: String,
      default: "",
    },
  },
  data() {
    return {
      number: 1,
      btnSwitch: false, //提交按钮防止重复提交
      type: "", //join_cart：加入购物车，buy_now：立即购买
      skuId: 0,
      limitNumber: 0, // 限购
    };
  },
  watch: {
    goodsDetail(newData, oldData) {
      this.skuId = newData.sku_id;
    },
    minBuy(newData, oldData) {
      if (this.minBuy > 1) {
        this.number = Number(this.minBuy);
      }
    },
  },
  methods: {
    open() {
      console.log("弹出层打开事件");
    },
    change(skuId, spec_id) {
      if (this.disabled) return;
      this.btnSwitch = false;
      this.skuId = skuId;
      // 清空选择
      for (var i = 0; i < this.goodsDetail.goods_spec_format.length; i++) {
        var sku = this.goodsDetail.goods_spec_format[i];
        for (var j = 0; j < sku.value.length; j++) {
          // 排除当前点击的规格值
          if (
            spec_id == this.goodsDetail.goods_spec_format[i].value[j].spec_id
          ) {
            this.goodsDetail.goods_spec_format[i].value[j].selected = false;
          }
        }
      }

      this.getGoodsSkuInfo();
    },
    close() {
      this.$emit("close");
    },
    // 获取普通商品详情
    getGoodsSkuInfo() {
      let res = this.$api.sendRequest({
        url: "/api/goodssku/info",
        data: {
          sku_id: this.skuId,
        },
        success: (res) => {
          let data = res.data;

          if (data != null) {
            data.unit = data.unit || "件";
            this.goodsSkuDetail = data;
            this.dealData();

            if (
              this.goodsSkuDetail.promotion_type == 1 &&
              this.goodsSkuDetail.discountTimeMachine
            ) {
              this.goodsSkuDetail.show_price =
                this.goodsSkuDetail.discount_price;
            }

            if (
              this.goodsSkuDetail.promotion_type == 1 &&
              this.goodsSkuDetail.discountTimeMachine
            ) {
              this.goodsSkuDetail.show_price =
                this.goodsSkuDetail.discount_price;
            } else if (this.goodsSkuDetail.member_price > 0) {
              this.goodsSkuDetail.show_price = this.goodsSkuDetail.member_price;
            } else {
              this.goodsSkuDetail.show_price = this.goodsSkuDetail.price;
            }

            this.btnSwitch = false;
            this.$emit("refresh", this.goodsSkuDetail);
          } else {
            this.$util.redirectTo("/pages/tabbar/index/index", {}, "reLaunch");
          }
        },
        fail: (res) => {
          this.btnSwitch = false;
          this.$util.redirectTo("/pages/tabbar/index/index", {}, "reLaunch");
        },
      });
    },
    //提交
    confirm(type) {
      // 删除待付款物流方式缓存
      uni.removeStorageSync("delivery");

      // if (!this.goodsDetail.stock || this.goodsDetail.stock == 0) {
      //   this.$util.showToast({
      //     title: "库存不足，暂无法购买！",
      //   });
      //   return;
      // }

      if (!uni.getStorageSync("token")) {
        this.$util.showToast({
          title: "请先登录",
        });
        return;
      }

      if (this.number.length == 0 || this.number == 0) {
        this.$util.showToast({
          title: "购买数量不能为0",
        });
        return;
      }

      // if (this.number > this.goodsDetail.stock) {
      //   this.$util.showToast({
      //     title: "库存不足",
      //   });
      //   return;
      // }

      if (this.btnSwitch) return;
      this.btnSwitch = true;
      if (type == "join_cart") {
        var data = {
          sku_id: this.skuId,
          num: this.number,
        };

        this.$api.sendRequest({
          url: "/api/cart/add",
          data: data,
          success: (res) => {
            var data = res.data;
            if (data > 0) {
              this.$util.showToast({
                title: "加入购物车成功",
              });
            }
            this.$emit("close");
            this.btnSwitch = false;
          },
          fail: (res) => {
            this.$emit("close");
            this.btnSwitch = false;
          },
        });
      } else if (type == "buy_now") {
        var data = {
          sku_id: this.skuId,
          num: this.number,
        };

        uni.setStorage({
          key: "orderCreateData",
          data: data,
          success: () => {
            this.$util.redirectTo("/otherpages/mall/submitOrder");

            this.btnSwitch = false;
          },
        });
        this.close();
      } else if (type == "pintuan") {
        var data = {
          pintuan_goods_id: this.goodsDetail.id,
          group_id: this.goodsDetail.group_id,
          num: this.number,
        };

        uni.setStorage({
          key: "pintuanOrderCreateData",
          data: data,
          success: () => {
            this.$util.redirectTo("/otherpages/mall/tuanSubmitOrder");
            this.btnSwitch = false;
          },
        });
      } else {
      }
    },
    dealData(item = this.goodsSkuDetail) {
      if (item.sku_images) item.sku_images = item.sku_images.split(",");
      else item.sku_images = [];

      // 多规格时合并主图
      if (item.goods_spec_format && item.goods_image) {
        item.goods_image = item.goods_image.split(",");
        item.sku_images = item.sku_images.concat(item.goods_image);
      }

      // 当前商品SKU规格
      if (item.sku_spec_format)
        item.sku_spec_format = JSON.parse(item.sku_spec_format);

      // 商品属性
      if (item.goods_attr_format) {
        let goods_attr_format = JSON.parse(item.goods_attr_format);
        item.goods_attr_format = this.$util.unique(
          goods_attr_format,
          "attr_id"
        );
        for (var i = 0; i < item.goods_attr_format.length; i++) {
          for (var j = 0; j < goods_attr_format.length; j++) {
            if (
              item.goods_attr_format[i].attr_id ==
                goods_attr_format[j].attr_id &&
              item.goods_attr_format[i].attr_value_id !=
                goods_attr_format[j].attr_value_id
            ) {
              item.goods_attr_format[i].attr_value_name +=
                "、" + goods_attr_format[j].attr_value_name;
            }
          }
        }
      }

      // 商品SKU格式
      if (item.goods_spec_format)
        item.goods_spec_format = JSON.parse(item.goods_spec_format);

      this.goodsDetail.unit = this.goodsDetail.unit || "件";
    },
    decreaseQuantity() {
		var min = 1;
      if (this.number > min) {
        this.number -= 1;
      } else {
        if (this.minBuy > 1) {
          this.$util.showToast({
            title: "该商品" + this.minBuy + this.goodsDetail.unit + "起售",
          });
        }
        return;
      }
      if (this.number > this.limitNumber && this.limitNumber) {
        this.number = this.limitNumber;
      }
    },
    increaseQuantity() {
      if (this.goodsDetail.stock == 0) return;
      var min = 1;
      var stock = this.goodsDetail.stock;

      if (this.maxBuy == 1) {
        stock = 1;
      }

      if (
        this.goodsDetail.is_limit == 1 &&
        this.maxBuy > 0 &&
        this.maxBuy < stock
      )
        stock = this.maxBuy;

      if (
        this.goodsDetail.is_limit == 1 &&
        this.goodsDetail.limit_type == 2 &&
        this.maxBuy > 0 &&
        this.goodsDetail.purchased_num > 0
      ) {
        let maxBuy = this.maxBuy - this.goodsDetail.purchased_num;
        stock =
          maxBuy < this.goodsDetail.stock ? maxBuy : this.goodsDetail.stock;
      }

      if (this.minBuy > 1) {
        min = this.minBuy;
      }

      if (this.number < stock) {
        this.number++;
      } else {
        if (this.number >= this.goodsDetail.stock) {
          this.$util.showToast({
            title: "库存不足",
          });
          return;
        }

        if (this.goodsDetail.is_limit == 1 && this.maxBuy > 0) {
          if (this.goodsDetail.limit_type == 1) {
            this.$util.showToast({
              title: "该商品每次最多购买" + this.maxBuy + this.goodsDetail.unit,
            });
            return;
          }

          if (this.goodsDetail.limit_type == 2) {
            let message =
              "该商品每人限购" + this.maxBuy + this.goodsDetail.unit;
            message +=
              this.goodsDetail.purchased_num > 0
                ? "，您已购买了" +
                  this.goodsDetail.purchased_num +
                  this.goodsDetail.unit
                : "";
            this.$util.showToast({
              title: message,
            });
            return;
          }
        }
      }
      if (this.number > this.limitNumber && this.limitNumber) {
        this.number = this.limitNumber;
      }
    },
    blur() {
      if (!this.number) {
        this.number = 0;
      }
      if (this.number > this.limitNumber && this.limitNumber) {
        this.number = this.limitNumber;
      }
      if (this.number < this.minNumber && this.minNumber) {
        this.number = this.minNumber;
      }

      if (
        this.goodsDetail.is_limit == 1 &&
        this.maxBuy > 0 &&
        this.number > this.maxBuy
      ) {
        this.number = this.maxBuy;
      }

      if (
        this.goodsDetail.is_limit == 1 &&
        this.maxBuy > 0 &&
        this.goodsDetail.purchased_num > 0
      ) {
        let maxBuy = this.maxBuy - this.goodsDetail.purchased_num;
        if (this.number > maxBuy) this.number = maxBuy;
      }
      if (this.number < this.minBuy && this.minBuy > 0) {
        this.number = this.minBuy;
      }

      if (this.number <= 0) {
        this.number = 1;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.popDialog {
  position: relative;
  padding: 40rpx 0;
  background-color: $color-bg;
  height: 75vh !important;
  border-radius: 20rpx;
  .goods {
    display: flex;
    align-items: center;
    .img {
      width: 160rpx;
      height: 160rpx;
      border-radius: 10rpx;
      margin-right: 24rpx;
    }
    .price {
      display: flex;
      align-items: baseline;
      font-weight: bold;
      color: $color-title2;
      font-size: 40rpx;
      i {
        font-weight: bold;
        color: $color-title2;
        font-size: $font-size-tag;
        font-style: normal;
      }
    }
  }
  .sku {
    height: calc(100% - 116rpx);
    box-sizing: border-box;
    .skuItem {
      display: inline-block;
      color: #656565;
      height: 56rpx;
      line-height: 56rpx;
      padding: 0 24rpx;
      background: #f7f7f7;
      margin-bottom: 20rpx;
      margin-right: 20rpx;
      border-radius: 30rpx;
    }
    .selected {
      background-color: $color-title2 !important;
      color: #fff !important;
    }
    .active {
      border: 2rpx solid #000000;
      color: #000000 !important;
    }
  }
}
.footer {
  display: flex;
  justify-content: space-between;
  .btn_com {
    height: 98rpx;
    line-height: 98rpx;
    text-align: center;
    box-sizing: border-box;
    border-radius: 60rpx;
  }
  .btn_cart {
    width: 228rpx;
    color: #fff;
    background: #ff9500;
  }
  .btn_buy {
    width: 426rpx;
    color: #fff;
    background-color: #fe7004;
  }
}

/* 数量控制 */
.quantity-control {
  display: flex;
  align-items: center;
  border: 1px solid #e7e8eb;
  border-radius: 40rpx;
}

.btn-minus,
.btn-plus {
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  font-size: 32rpx;
  color: #333;
  margin: 0 10rpx;
  font-weight: bold;
}

.quantity {
  font-size: 32rpx;
  margin: 0 20rpx;
}

.tagbox {
  display: flex;
  flex-wrap: wrap;
  .tags {
    height: 70rpx;
    line-height: 70rpx;
    width: 140rpx;
    text-align: center;
    overflow: hidden;
    border-radius: 24rpx;
    background: #f8f9fc;
    margin-right: 20rpx;
    margin-bottom: 20rpx;
    font-size: 24rpx;
    &:nth-child(4n) {
      margin-right: 0;
    }
  }
}
.quantity {
  text-align: center;
  width: 30rpx;
}
</style>
